<?php 
namespace app\admin\controller;
use think\Db;
use app\common\controller\Adminbase;
use think\facade\Session;
use app\admin\model\Gtask as TaskModel;
use app\admin\model\Product as ProductModel;
use app\admin\model\Procedure as ProcedureModel;
use app\admin\model\AdminUser;
use app\admin\model\Gongdan as GongdanModel;
use app\admin\model\Wages as WagesModel;
use app\admin\model\Booking as BookingModel;

class Booking extends Adminbase
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $this->modelClass = new BookingModel();
            list($page, $limit, $where) = $this->buildTableParames();
            $_list = $this->modelClass->where($where)->where('deleted',0)->order('id DESC')
            ->page($page, $limit)
            ->select();
            $count = $this->modelClass
            ->where($where)
            ->count();
            foreach($_list as $k=>$row){
                $baogongNums = '';
                $goodNums = '';
                $badnums = '';
                $product = ProductModel::find($row['product_id']);
                $_list[$k]['product_nums'] = $product['nums'];
                $_list[$k]['product_title'] = $product['title'];
                $_list[$k]['product_guige'] = $product['guige'];
                $procedure = ProcedureModel::find($row['procedure_id']);
                $_list[$k]['procedure_nums'] = $procedure['nums'];
                $_list[$k]['procedure_title'] = $procedure['title'];
                $task = TaskModel::find($row['task_id']);
                $gongdan = GongdanModel::find($task['gongdan_id']);  
                $_list[$k]['total'] = $gongdan['total'];
                $_list[$k]['gongdan_nums'] = $gongdan['nums'];
                $baogong = json_decode($row['baogong'],true);
                foreach($baogong as $kk=>$v){
                    $baogongNums .= $v['attr'].':'.$v['nums'].'份,';
                }
                $_list[$k]['baogong'] = $baogongNums;
                $good = json_decode($row['good'],true);
                foreach($good as $kk=>$v){
                    $goodNums .= $v['attr'].':'.$v['nums'].'份,';
                }
                $_list[$k]['good'] = $goodNums;
                $bad = $row['bad']?json_decode($row['bad'],true):[];
                foreach($bad as $kk=>$v){
                    if(!empty($v)){
                        $a = json_decode($v,true);
                        $total = 0;
                        // dg($a);
                        foreach($a as $row2){
                            $total += (int)$row2['nums'];
                        }
                        $badnums .= $good[$kk]['attr'].':'.$total.'份,';
                    }
                }
                $_list[$k]['bad'] = $badnums;
                $wages = $this->findWages($row['product_id'],$row['procedure_id']);
                $_list[$k]['wages_types'] = $row['wages_type']==1?'计件':'计时';
                $_list[$k]['prices'] = $wages['prices'];
                $_list[$k]['pro_user'] = AdminUser::getAdmin($row['user_id'],'nickname');
                $_list[$k]['approve'] = $row['approve']?'已审核':'未审核';
            }
            $result = array("code" => 0, 'count' => $count, "data" => $_list);
            return json($result);
        }
        return $this->fetch();
    }

    public function add()
    {
        if($this->request->post()){
            $data = $this->request->param();
            if(!$data['end_time']){
                $data['end_time'] = date('Y-m-d H:i:s');
            }
            if(!$data['hours']){
                $this->error('请输入工时');
            }
            $task = TaskModel::find($data['procedure_id']);
            $good = [];
            $nums = [];
            BookingModel::insertCensus($data['jsonstring']);
            // $jsonstring = json_decode($data['jsonstring'],true);
            foreach($data['attr'] as $k=>$row){
                if((int)$data['goodnums'][$k] + (int)$data['badnums'][$k] != (int)$data['nums'][$k]){
                    $this->error('报工数量与实际产量不符');
                }
                $good[] = ['attr'=>$row,'nums'=>$data['goodnums'][$k]];
                $nums[] = ['attr'=>$row,'nums'=>$data['nums'][$k]];
            }
            foreach($data['goodnums'] as $n){
                $total += (int)$n;
            }
            $wages = $this->findWages($task['procedure_id'],$data['product_id']);
            $prices = 0;
            if($wages){
                $prices = $total * $wages['prices'];
            }
            $insertData = [
                'task_id'=>$data['procedure_id'],
                'product_id'=>$data['product_id'],
                'procedure_id'=>$task['procedure_id'],
                'user_id'=>$data['user_id'],
                'baogong'=>json_encode($nums),
                'good'=>json_encode($good),
                'bad'=>json_encode($data['jsonstring']),
                'begin_time'=>$data['begin_time'],
                'end_time'=>$data['end_time'],
                'time'=>$data['hours']*60+(int)$data['minutes'],
                'efficiency'=>$total/($data['hours']+($data['minutes']?$data['minutes']/60:0)),
                'standard'=>$data['dabiao']=='已达标'?1:0,
                'approve'=>$data['status'],
                'approve_user'=>session('admin_user_auth')['uid'],
                'wages'=>$prices,
                'wages_type'=>$wages?$wages['type']:0,
                'addtime'=>date('Y-m-d H:i:s')
            ];
            // dg($insertData);
            // exit();
            BookingModel::insertGetId($insertData);
            $this->success('添加成功');
        }
        //工单编号
        $gongdanList = GongdanModel::where(['status'=>1,'deleted'=>0])->select();
        //审批人
        $admin_id = session('admin_user_auth')['uid'];
        $this->assign('gongdan',$gongdanList);
        $this->assign('admin',AdminUser::getAdmin($admin_id,'nickname'));
        return $this->fetch();
    }

    public function edit()
    {
        if($this->request->post()){
            $data = $this->request->param();
            // dg($data);
            // exit();
            if(!$data['end_time']){
                $data['end_time'] = date('Y-m-d H:i:s');
            }
            $booking = BookingModel::find($data['id']);
            $task = TaskModel::find($booking['task_id']);
            // dg($task);
            $product = ProductModel::find($booking['product_id']);
            $good = [];
            $nums = [];
            // $jsonstring = json_decode($data['jsonstring'],true);
            foreach($data['attr'] as $k=>$row){
                if((int)$data['goodnums'][$k] + (int)$data['badnums'][$k] != (int)$data['nums'][$k]){
                    $this->error('报工数量与实际产量不符');
                }
                $good[] = ['attr'=>$row,'nums'=>$data['goodnums'][$k]];
                $nums[] = ['attr'=>$row,'nums'=>$data['nums'][$k]];
            }
            $total = 0;
            foreach($data['goodnums'] as $n){
                $total += (int)$n;
            }
            $wages = $this->findWages($task['procedure_id'],$product['id']);
            $prices = 0;
            if($wages){
                $prices = $total * $wages['prices'];
            }
            TaskModel::where('id',$task['id'])->update(['status'=>$data['gx_status']]);
            $insertData = [
                'user_id'=>$data['user_id'],
                'baogong'=>json_encode($nums),
                'good'=>json_encode($good),
                'bad'=>json_encode($data['jsonstring']),
                'begin_time'=>$data['begin_time'],
                'end_time'=>$data['end_time'],
                'time'=>$data['hours']*60+(int)$data['minutes'],
                'efficiency'=>$total/($data['hours']+($data['minutes']?$data['minutes']/60:0)),
                'standard'=>$data['dabiao']=='已达标'?1:0,
                'approve'=>$data['status'],
                'approve_user'=>session('admin_user_auth')['uid'],
                'wages'=>$prices,
                'wages_type'=>$wages?$wages['type']:0,
                'addtime'=>date('Y-m-d H:i:s')
            ];
            // dg($insertData);
            // exit();
            BookingModel::where('id',$data['id'])->update($insertData);
            $this->success('修改成功');
        }
        $id = $this->request->param('id');
        $booking = BookingModel::find($id);
        $procedure = ProcedureModel::find($booking['procedure_id']);
        $product = ProductModel::find($booking['product_id']);
        $task = TaskModel::find($booking['task_id']);
        $wages = $this->findWages($booking['product_id'],$booking['procedure_id']);
        //工序信息
        $taskList = TaskModel::where(['gongdan_id'=>$task['gongdan_id'],'deleted'=>0])->select();
        
        //工单编号
        $gongdan = GongdanModel::find($task['gongdan_id']);
        $this->assign('gongdan',$gongdan);
        //工序名称
        $procedure = ProcedureModel::find($booking['procedure_id']);
        $this->assign('procedure',$procedure);
        $this->assign('product',$product);
        
        //用户列表
        $userList = [];
        $auth = explode(',',$procedure['auth']);
        if(in_array(0,$auth)){
            $userList = AdminUser::where(['status'=>1])->field('nickname,id')->select();
        }else{
            $userList = AdminUser::where(['id'=>$auth,'status'=>1])->field('nickname,id')->select();
        }
        $this->assign('userList',$userList);
        $booking['baogong'] = json_decode($booking['baogong'],true);
        $booking['good'] = json_decode($booking['good'],true);
        // dg($booking['good']);
        $bad = $booking['bad']?json_decode($booking['bad'],true):[];
        // dg($bad);
        foreach($bad as $k=>$row){
            $a = json_decode($row,true);
            $total = 0;
            foreach($a as $k2=>$row2){
                $total += (int)$row2['nums'];
            }
            $badNums[] = [
                // 'attr'=>$a[2],
                'nums'=>$total
            ];
        }
        // dg($badNums);
        $badList = [];
        foreach($bad as $k=>$row){
            $a = json_decode($row,true);
            unset($a[2]);
            $badList[] = json_encode($a);
        }
        $booking['badList'] = $badList;
        $booking['bad'] = $badNums;
        $booking['hours'] = floor($booking['time']/60);
        $booking['minutes'] = floor($booking['time']-$booking['time']/60*60);
        // dg($booking);
        $wages['biaozhun'] = $wages['counts'].'/'.floor($wages['minutes']/60).'时'.floor($wages['minutes']-$wages['minutes']/60*60).'分';
        // dg($task);
        $this->assign('booking',$booking);
        $this->assign('task',$task);
        $this->assign('wages',$wages);
        $this->assign('admin',AdminUser::getAdmin($admin_id,'nickname'));
        return $this->fetch();

    }

    //工单信息
    public function findGD()
    {
        $id = $this->request->param('id');
        $admin_id = session('admin_user_auth')['uid'];
        $gongdan = GongdanModel::find($id);
        //产品信息
        $product = ProductModel::field('nums,title,guige,id')->find($gongdan['product_id']);
        //工序信息
        $taskList = TaskModel::where(['gongdan_id'=>$id,'deleted'=>0])->select();
        $procedureList = [];
        foreach($taskList as $k=>$row){
            $procedure = ProcedureModel::where('deleted',0)->find($row['procedure_id']);
            //有权限的工序
            $auth = explode(',',$procedure['auth']);
            if(!empty($procedure) && (in_array(0,$auth) || in_array($admin_id,$auth))){
                $procedureList[] = [
                    'id'=>$row['id'],
                    'procedute_id'=>$procedure['id'],
                    'title'=>$procedure['title'],
                    'status'=>$row['status']
                ];
            }
        }
        $userList = [];
        if(!empty($procedureList)){  //默认第一个用户权限
            $procedureA = ProcedureModel::where('deleted',0)->find($procedureList[0]['procedute_id']);
            $auth = explode(',',$procedureA['auth']);
            if(in_array(0,$auth)){
                $userList = AdminUser::where(['status'=>1])->field('nickname,id')->select();
            }else{
                $userList = AdminUser::where(['id'=>$auth,'status'=>1])->field('nickname,id')->select();
            }
        }
        $task = $taskList[0];
        $wages = $this->findWages($gongdan['product_id'],$procedureA['id']);
        if(!$wages){
            $wages = [];
        }
        //已报工单
        $bookList = BookingModel::where('task_id',$task['id'])->select();
        // dg($bookList);
        if(!empty($bookList)){
            $plan = json_decode($task['plan'],true);
            foreach($bookList as $k=>$row){
                $baogong = json_decode($row['baogong'],true);
                foreach($baogong as $k=>$row2){
                    if($plan[$k]['key'] == $row2['attr']){
                        $plan[$k]['nums'] -= $row2['nums'];
                    }
                }
            }
            $task['plan'] = json_encode($plan);
        }
        return json(['product'=>$product,'procedureList'=>$procedureList,'procedureA'=>$procedureA,'userList'=>$userList,'task'=>$task,'wages'=>$wages]);
    }

    public function findGX()
    {
        $id = $this->request->param('id');
        $product_id = $this->request->param('product_id');
        $admin_id = session('admin_user_auth')['uid'];
        $task = TaskModel::where(['deleted'=>0])->find($id);

        
        $bookList = BookingModel::where('task_id',$task['id'])->select();
        if(!empty($bookList)){
            $plan = json_decode($task['plan'],true);
            foreach($bookList as $k=>$row){
                $baogong = json_decode($row['baogong'],true);
                foreach($baogong as $k=>$row2){
                    if($plan[$k]['key'] == $row2['attr']){
                        $plan[$k]['nums'] -= $row2['nums'];
                    }
                }
            }
            $task['plan'] = json_encode($plan);
        }
        
        // dg($task);
        $procedure = ProcedureModel::where('deleted',0)->find($task['procedure_id']);
        $auth = explode(',',$procedureA['auth']);
        if(in_array(0,$auth)){
            $userList = AdminUser::where(['status'=>1])->field('nickname,id')->select();
        }else{
            $userList = AdminUser::where(['id'=>$auth,'status'=>1])->field('nickname,id')->select();
        }
        $wages = $this->findWages($product_id,$task['procedure_id']);
        if(!$wages){
            $wages = [];
        }
        return json(['userList'=>$userList,'task'=>$task,'wages'=>$wages]);
    }

    public function badL()
    {
        $id = $this->request->param('id');
        //工序
        $procedure = ProcedureModel::where('deleted',0)->find($id);
        //工序不良项
        $badIds = explode(',',$procedure['bad_ids']);
        $badList = Db::name('gd_bad')->where(['id'=>$badIds])->select();
        // dg($badList);
        $this->assign('badList',$badList);
        return $this->fetch();
    }
    
    //取消，删除
    public function delete()
    {
        $id = $this->request->param('id');
        BookingModel::where('id',$id)->delete();
        $this->success('取消成功');
    }
    //报工效率
    public function findWages($procedure_id,$product_id)
    {
        $wages = WagesModel::where(['product_id'=>$product_id,'procedure_id'=>$procedure_id,'deleted'=>0])->find();
        return $wages;
    }

    public function getAttr()
    {
        $taskId = $this->request->param('id');
    }
}